package org.bookie.init.tasks;

import java.util.Properties;

import org.apache.hivemind.Registry;
import org.bookie.init.InitTask;
import org.bookie.model.Group;
import org.bookie.model.User;
import org.bookie.model.services.GroupDAO;
import org.bookie.model.services.UserDAO;

public class GroupLoad implements InitTask {
	private boolean empty;

	public Properties check(Registry registry) throws Exception {
		Properties result = new Properties();
		GroupDAO groupDAO = (GroupDAO) registry.getService(GroupDAO.class);
		empty = groupDAO.findAll().isEmpty();
		result.put("Groups found", String.valueOf(!empty));
		return result;
	}

	public Properties execute(Registry registry) throws Exception {
		Properties result = new Properties();
		if(empty){
			Group g1 = new Group(UserLoad.SIMPSON+" family");
			Group g2 = new Group(UserLoad.BOUVIER+" family");
			Group g3 = new Group(UserLoad.FLANDERS+" family");
			Group g4 = new Group("Others");
			Group[] groups = new Group[]{g1, g2, g3, g4};
			GroupDAO groupDAO = (GroupDAO) registry.getService(GroupDAO.class);
			for(Group group:groups){
				groupDAO.makePersistent(group);
				result.put("Created group", group.getName());
			}
			UserDAO userDAO = (UserDAO) registry.getService(UserDAO.class);
			for(User user : userDAO.findAll()){
				if(user.getUsername().endsWith(UserLoad.SIMPSON)){
					addGroup(result, user, g1);
				}else if(user.getUsername().endsWith(UserLoad.BOUVIER)){
					addGroup(result, user, g2);
				}else if(user.getUsername().endsWith(UserLoad.FLANDERS)){
					addGroup(result, user, g3);
				}else{
					addGroup(result, user, g4);
				}
			}
		} else {
			result.put("Group update", "Skipped");
		}
		return result;
	}
	
	private void addGroup(Properties result, User user, Group group){
		user.addGroup(group);
		result.put("User "+user.getEmail()+" is participating in group", group.getName());
	}

	public String getTitle() {
		return "Group load";
	}

}
